from django.shortcuts import render
# 引入datetime
from datetime import datetime
# 引入数据库操作模块
from utils import sqlhelper
# Json
from django.http import JsonResponse


def index(request):
    # 获取今天的天气
    today = datetime.now().strftime("%Y-%m-%d")
    return render(request, 'weatherweb/cityweather.html', {'date': today})


def list_values(request):
    """获取数据"""
    # 获取查询条件
    q_str = request.POST
    page = int(request.POST.get('page'))
    limit = int(request.POST.get('limit'))
    # 准备查询语句
    sql ="""
        Select T2.Province,T1.Area,date,Weather,windd,winds,hight,low
    from CityWeather As T1 
    Inner Join CityURL AS T2 on T1.Area = T2.Area
    Where Date='%s' And T2.Province Like '%s' And T1.Area Like '%s'
    """ % (q_str.get('q_date'),"%" + q_str.get('q_province') + "%","%" +q_str.get('q_city')+ "%")

    # 执行
    response = sqlhelper.get_db_data_dict(sql, ['province','area', 'date', 'weather', 'windd', 'winds', 'hight', 'low'])
    # 定义一个返回值数据结构
    res = {'code': 0, 'count': 0, 'data': 0, 'error': ''}
    # 判断：
    if response.get('status'):
        one_page = response['data'][(page - 1) * limit: page * limit]
        res['count'] = len(response['data'])
        res['data'] = one_page
    else:
        res['error'] = response['error']

    return JsonResponse(res)
